package pub.guoxin.oops.common.auth.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import pub.guoxin.oops.annotation.InjectUser;
import pub.guoxin.oops.common.auth.JwtUserVo;
import pub.guoxin.oops.common.base.exception.InjectUserException;
import pub.guoxin.oops.model.User;
import pub.guoxin.oops.repository.UserRepository;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * Created by guoxin on 17-11-24.
 */
@Slf4j
@Aspect
@Component
public class InjectUserAspect {

    @Autowired
    private UserRepository userRepository;

    @Pointcut("execution(* pub.guoxin.oops..*Controller.*(..))")
//    @Pointcut("(execution(* pub.guoxin.oops..*Controller.*(..))) || (execution(* pub.guoxin.oops..*Endpoint.*(..)))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod(); //被拦截方法
        Object[] args = pjp.getArgs();
        for (int i = 0; i < args.length; i++) { // 参数列表
            MethodParameter methodParameter = new SynthesizingMethodParameter(method, i);
            Class<?> parameterType = methodParameter.getParameterType();
            if (!parameterType.equals(User.class)){
                continue;
            }
            Annotation[] annotations = methodParameter.getParameterAnnotations();
            // 循环参数上所有的注解
            for (Annotation annotation : annotations) {
                if (!(annotation instanceof InjectUser)) {
                    continue;
                }
                JwtUserVo jwtUser =(JwtUserVo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                if (Objects.isNull(jwtUser)){
                    throw new InjectUserException("User not found");
                }
                String mobile = jwtUser.getMobile();
                User user = userRepository.findByMobile(mobile);
                if (Objects.isNull(user)){
                    throw new InjectUserException("User not found");
                }
                args[i] = user;
                break;
            }
        }
        return pjp.proceed(args);
    }
}
